package com.gxa.springboot229.controller;

import com.gxa.springboot229.excption.BusinessException;
import com.gxa.springboot229.util.JsonResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 异常处理
 *
 */
@RestController
@ControllerAdvice
public class ExceptionController {

    @ExceptionHandler
    public Map hander(Exception e){
        JsonResult jsonResult = new JsonResult();
        // 当业务层抛出异常时
        //throw new BusinessException("手机号重复")
        if(e instanceof BusinessException){
            jsonResult.setCode("0");
            //把系统异常信息带返还给前端
            jsonResult.setMsg(e.getMessage());
        }else {
            jsonResult.setCode("500");
            jsonResult.setMsg("系统开小差了");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println("---------- "+format.format(new Date())+"-------------");
            //System.out.println(e.toString());

            //开发中才用，上线 不能用
            e.printStackTrace();
        }
        return jsonResult.getValues();
    }
}
